<template>
	<view class="chat_room_main">
		<view class="top_return_username_dots">
			<view class="top_left">
				<view class="return_view" @click="returnPreviousPage">
					<uni-icons type="left" size="26"></uni-icons>
				</view>
				<view class="username_view_text">
					{{userName}}
				</view>
			</view>
			<view class="top_right" @click="clickDots">
				<uni-icons type="more-filled" size="28" color="#5f5f5f"></uni-icons>
			</view>
		</view>
		<view class="messages_contain" @touchmove.passive="touchMoveHandler">
			<view class="message_per" v-for="(message,index) in messages" :key="index">
				<view class="left_user_messages" v-if="!message.isMe">
					<view class="left_user_avatar" @click="toUserDetail">
						<image :src="userAvatar" mode="aspectFill" class="user_avatar"></image>
					</view>
					<view class="left_user_messages_text" v-if="!message.isMe">
						<view class="type-content" v-if="message.type === 'text'">
							{{message.content}}
						</view>
						<view class="image-message" v-if="message.type === 'image'" @click="previewImage(message)">
							<image :src="message.content" mode="aspectFill"></image>
						</view>
						<view class="message-video" v-if="message.type === 'video'">
							<DomVideoPlayer :src="message.content" :autoplay="false" muted :isLoading="true"></DomVideoPlayer>
						</view>
						<view class="audio-content" v-if="message.type === 'audio'">
							<my-audio-message :audioUrl="message.content" :audioTime="10" :index="index"
								:isPlaying="currentPlayingIndex === index" @playAudio="playAudio(index)"
								@pauseAudio="pauseAudio(index)"></my-audio-message>
						</view>
					</view>
				</view>
				<view class="right_box">
					<view class="right_my_messages" v-if="message.isMe">
						<view class="type-content" v-if="message.type === 'text'">
							{{message.content}}
						</view>
						<view class="image-message" v-if="message.type === 'image'" @click="previewImage(message)">
							<image :src="message.content" mode="aspectFill"></image>
						</view>
						<view class="message-video" v-if="message.type === 'video'">
							<DomVideoPlayer :src="message.content" :autoplay="false" muted :isLoading="true"></DomVideoPlayer>
						</view>
						<view class="audio-content" v-if="message.type === 'audio'">
							<my-audio-message :audioUrl="message.content" :audioTime="10" :index="index"
								:isPlaying="currentPlayingIndex === index" @playAudio="playAudio(index)"
								@pauseAudio="pauseAudio(index)"></my-audio-message>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom_input">
			<view class="container-sender">
				<!-- 键盘，语音 -->
				<view class="voice_view" @click="changeInputMethods">
					<uni-icons type="mic" size="26" color="#000000" v-if="!isVoice"></uni-icons>
					<image src="@/static/icons/keywords.png" mode="aspectFill" class="smile_face" v-else></image>
				</view>
				<!-- 输入框 -->
				<view class="input_view" @longpress="longpressVoice" @touchend="stopVoice"
					@touchmove="touchMoveDuringRecord">
					<uni-easyinput :disabled="inputDisable" :clearable="false" primaryColor="#66596b" confirmType="发送"
						v-model="inputMessage" :placeholder="placeholderText" :inputBorder="false"></uni-easyinput>
				</view>
				<!-- 表情 -->
				<view class="expression_view" @click="openEmojiList">
					<image src="@/static/icons/smile.png" mode="aspectFill" class="smile_face"></image>
				</view>
				<!-- 发送图标 -->
				<view class="muiltipily_view" @click="sendMessage" v-if="!isInputEmpty">
					<image src="@/static/icons/send.png" mode="aspectFill"></image>
				</view>
				<!-- 加号 -->
				<view class="muiltipily_view" @click="clickPlusempty" v-else>
					<uni-icons type="plusempty" size="26" color="#000000"></uni-icons>
				</view>
			</view>
			<!-- 表情库 -->
			<view class="emojis-show" v-show="emojiShow">
				<view class="emoji-item" v-for="(item,index) in emojiList" :key="index" @click="emojiToInput(item)">
					{{item}}
				</view>
			</view>
			<!-- 发送照片，拍照，位置等 -->
			<view class="other-sender" v-show="otherShow">
				<view class="other-sender-item" v-for="(item,index) in otherSenderList" :key="index"
					@click="clickOther(item)">
					<view class="other-sender-image">
						<image :src="item.img" mode="aspectFill"></image>
					</view>
					<view class="other-sender-text">
						{{item.text}}
					</view>
				</view>
			</view>
		</view>

		<uni-popup ref="popup" type="center" border-radius="10px 10px 10px 10px">
			<view class="tip-main">
				<view class="audio-icon">
					<image src="@/static/icons/mic-on.png" mode="aspectFill" v-if="!isRecording"></image>
					<image src="@/static/icons/mic-off.png" mode="aspectFill" v-else></image>
				</view>
				<view class="tip-text">
					{{tipText}}
				</view>
			</view>
		</uni-popup>


	</view>
</template>

<script>
	import MyAudioMessage from '@/components/common-components/MyAudioMessage.vue';
	import {
		emojiList
	} from '@/common/emoji/emoji';
	import { dateFormatString } from '@/common/util.js';
	import eventBus from '@/common/mitt/eventBus.js';
	import {
		client
	} from '@/request/alioss';
	import {
		saveMessage,getMessages,
		sendMessageTo
	} from '@/request/chat.js'
	const recorderManager = uni.getRecorderManager();
	export default {
		components: {
			MyAudioMessage
		},
		data() {
			return {
				currentPlayingIndex: null, // 当前正在播放的录音的索引
				tipText: '上滑取消发送',
				tipPopShow: false, // 长按发送的时候显示
				inputDisable: false,
				otherShow: false,
				otherSenderList: [{
						img: '../../../static/icons/photo.png',
						text: '照片'
					},
					{
						img: '../../../static/icons/take_photo.png',
						text: '拍照'
					},
					{
						img: '../../../static/icons/postion.png',
						text: '位置'
					}
				],
				emojiList: emojiList,
				emojiShow: false, // 控制表情包的显示与隐藏
				placeholderText: '请输入内容',
				isVoice: false,
				userAid: 0,
				inputMessage: '',
				userName: '',
				userAvatar: '',
				messages: [
					// {
					// 	messageAid: 1,
					// 	content: '你好！',
					// 	isMe: true,
					// 	time: '2024-10-31 10:00:00',
					// 	type: 'text',
					// },
					// {
					// 	messageAid: 2,
					// 	content: '有什么能帮你的吗？',
					// 	isMe: false,
					// 	time: '2024-10-31 10:00:03',
					// 	type: 'text',
					// },
					// {
					// 	messageAid: 3,
					// 	content: '咨询一下',
					// 	isMe: true,
					// 	time: '2024-10-31 10:01:00',
					// 	type: 'text',
					// },
					// {
					// 	messageAid: 4,
					// 	content: 'https://img2.baidu.com/it/u=97783964,1336098738&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1068',
					// 	isMe: true,
					// 	time: '2022-10-31 10:01:00',
					// 	type: 'image',
					// },
					// {
					// 	messageAid: 5,
					// 	content: '你觉得我们家的商品咋样？',
					// 	isMe: false,
					// 	time: '2024-10-31 10:01:40',
					// 	type: 'text',
					// },
					// {
					// 	messageAid: 6,
					// 	content: '质量很好，我很喜欢！',
					// 	isMe: true,
					// 	time: '2024-10-31 10:02:20',
					// 	type: 'text',
					// },
					// {
					// 	messageAid: 7,
					// 	content: 'https://cdn.freesound.org/previews/780/780272_12880153-lq.mp3',
					// 	isMe: true,
					// 	time: '2024-12-26 17:00:00',
					// 	type: 'audio',
					// 	audioTime: '2″'
					// },
					// {
					// 	messageAid: 8,
					// 	content: 'https://cdn.freesound.org/previews/776/776661_15232790-lq.mp3',
					// 	isMe: false,
					// 	time: '2020-12-05 17:00:00',
					// 	type: 'audio',
					// 	audioTime: '19″'
					// },
					// {
					// 	messageAid: 9,
					// 	content: 'https://img1.baidu.com/it/u=976982544,1209571331&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=785',
					// 	isMe: false,
					// 	time: '2023-10-31 10:01:00',
					// 	type: 'image',
					// },
				], // 聊天记录
				recordedFilePath: '', // 录音文件路径
				isRecording: false, // 标记是否正在录音
				startTime: 0, // 开始录音的时间
				isLongpress: false, // 是否长按
				sendData: {

				}, // 发送对象
			}
		},
		onLoad(options) {
			this.userAid = options.userAid
			// 获取聊天消息内容
			this.getMessagesFunc();
			// 排列消息（根据时间前后）
			this.sortMessage();
			let self = this;
			recorderManager.onStop(function(res) {
				console.log('录音结束：' + JSON.stringify(res));
				self.recordedFilePath = res.tempFilePath;
			});
			recorderManager.onError((err) => {
				console.error('录音出错', err);
			});
		},
		computed: {
			isInputEmpty() {
				return this.inputMessage.trim() === '';
			}
		},
		created() {
			const that = this;
			eventBus.on('selectedAddress', (data) => {
				if (data) {
					console.log(data);
					// 直接发送消息（位置信息）
					that.sendMessage();
				}
			});
		},
		beforeDestroy() {
			eventBus.off('selectedAddress');

		},

		methods: {
			
			// 获取聊天消息内容
			getMessagesFunc(){
				// console.log(this.userAid);
				getMessages({userAid: this.userAid}).then(res=>{
					// console.log(res);
					this.messages = res.data.data.messages;
					this.userName = res.data.data.userName;
					this.userAvatar = res.data.data.userAvatar;
				})
			},

			previewImage(message) {
				uni.previewImage({
					urls: [message.content],
					current: message.content
				});
			},

			// 返回上一页
			returnPreviousPage() {
				uni.navigateBack();
			},
			// 排列消息（根据时间前后）
			sortMessage() {
				this.messages.sort((a, b) => {
					const dateA = new Date(a.time);
					const dateB = new Date(b.time);
					return dateA - dateB;
				});
			},

			// 发送消息
			sendMessage() {
				// const date = new Date();
				this.sendData = [];
				this.sendData = {
					content: this.inputMessage,
					isMe: true,
					// time: dateFormatString(date),
					type: 'text',
					userAid: this.userAid
				}
				console.log(this.sendData);
				sendMessageTo(this.sendData).then(res=>{
					console.log(res);
					if(res.data.code === 10000){
						this.messages.push(this.sendData);
						this.inputMessage = '';
					}else{
						uni.showToast({
							title: '发送失败，请稍后再试...',
							icon: 'none'
						})
					}
				}).catch(err=>{
					console.error(err);
					uni.showToast({
						title: '发送失败，请稍后再试...',
						icon: 'none'
					})
				})
			},

			// 长按录音
			longpressVoice() {
				if (this.inputDisable) {
					console.log("开始录音");
					this.placeholderText = "松开 发送";
					this.isRecording = false;
					this.isLongpress = true;
					this.startTime = new Date().getTime(); // 记录开始时间
					// 开始录音
					recorderManager.start();
					this.$refs.popup.open();
				}
			},

			// 处理录音文件，例如发送到服务器
			handleRecordedFile() {
				console.log('录音文件路径:', this.recordedFilePath);
				// 先把录音文件上传到阿里云oss，在把返回的URL存储到后端MySQL中
				const objectKey = 'audio/' + uni.getStorageInfoSync("userName") + new Date().getTime() + '.mp3';
				client().then(ossClient => {
					ossClient.put(objectKey, this.recordedFilePath).then((result) => {
						console.log(result);
						const url = result.url; // 获取上传成功后的文件 URL
						const data = {
							inputMessage: url,
							dataType: 'audio',
						}
						this.senderDataToService(data); // 将 URL 发送到后端存储
					}).catch((err) => {
						console.error('上传到 OSS 失败', err);
						uni.showToast({
							title: '请稍后再试...',
							icon: 'none'
						})
					});
				})
			},

			// 将 message-data 发送到后端存储
			senderDataToService(data) {
				saveMessage(data).then(res => {
					console.log(res);
				})
			},

			// 手指抬起结束录音
			stopVoice() {
				if (this.inputDisable && this.isLongpress) {
					// console.log("录音结束");
					this.placeholderText = "按住 说话";
					const endTime = new Date().getTime();
					const duration = endTime - this.startTime;
					console.log(duration);
					if (duration >= 1000) { // 仅当录音时长超过 1 秒
						recorderManager.stop();
						this.handleRecordedFile();
					} else {
						// 录音时长不足 1 秒，可添加相应处理，例如提示用户
						uni.showToast({
							title: '时长过短，请重新录制',
							icon: 'none',
							duration: 1000,
						});
					}
					this.tipText = "上滑取消发送";
					this.$refs.popup.close();
					this.isLongpress = false;
				}
			},

			// 去用户主页
			toUserDetail() {
				uni.navigateTo({
					url: `/pages/tabBar/template/userDetailPage?aid=${this.userAid}`
				})
			},

			// 点击键盘或者录音图标转换输入方式
			changeInputMethods() {
				// this.emojiShow = false;
				if (this.isVoice) {
					this.isVoice = false;
					this.placeholderText = "请输入内容";
					this.inputDisable = false;
				} else {
					this.isVoice = true;
					this.inputDisable = true;
					this.placeholderText = "按住 说话";
					this.inputMessage = '';
				}
			},

			// 点击笑脸打开表情包库
			openEmojiList() {
				this.otherShow = false;
				this.emojiShow = !this.emojiShow;
			},

			// 按住上滑（取消录音）
			touchMoveDuringRecord() {
				if (this.inputDisable) {
					console.log("上滑取消");
					this.tipText = "松开取消发送";
					this.isRecording = true;
				}
			},

			// 点击加号
			clickPlusempty() {
				if (this.emojiShow) {
					this.emojiShow = false;
				}
				this.otherShow = !this.otherShow;
			},

			// 点击表情，让表情去输入框
			emojiToInput(item) {
				// 获取输入框光标的位置
				// uni.getSelectedTextRange({
				// 	success(res) {
				// 		console.log(res);
				// 	},
				// 	fail(err) {
				// 		console.log(err);
				// 	}
				// })
				if (!this.inputDisable) {
					this.inputMessage += item;
				}
			},

			clickOther(item) {
				if (item.text === '照片') {
					uni.chooseImage({
						count: 9, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album'], //从相册选择
						success: function(res) {
							console.log(JSON.stringify(res.tempFilePaths));
						}
					});
				} else if (item.text === '拍照') {
					uni.chooseImage({
						count: 9, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['camera'], //拍照
						success: function(res) {
							console.log(JSON.stringify(res.tempFilePaths));
						}
					});
				} else if (item.text === '位置') {
					// 打开地图组件定位
					uni.navigateTo({
						url: '/pages/common-compoent/MapContainer'
					})

				}
			},

			// 滑动消息区域
			touchMoveHandler(e) {
				// e.preventDefault();
				this.emojiShow = false;
				this.otherShow = false;
			},

			playAudio(index) {
				if (this.currentPlayingIndex !== null && this.currentPlayingIndex !== index) {
					// 暂停之前正在播放的音频
					this.pauseAudio(this.currentPlayingIndex);
				}
				this.currentPlayingIndex = index;
			},
			pauseAudio(index) {
				this.currentPlayingIndex = null;
			},
			clickDots(){
				uni.showToast({
					title: '敬请期待',
					icon: 'none'
				})
			},
		}
	}
</script>

<style scoped>
	.top_return_username_dots {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		position: sticky;
		top: 0;
		z-index: 100;
		background-color: #ffffff;
		padding-top: 25px;
		padding-bottom: 10px;
		padding-left: 20px;
		padding-right: 20px;
	}

	.top_left {
		display: flex;
		flex-direction: row;
	}

	.username_view_text {
		margin-left: 10px;
		font-size: 20px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		letter-spacing: 1px;
	}

	.messages_contain {
		padding-top: 30rpx;
		padding-left: 40rpx;
		padding-right: 40rpx;
		margin-top: 20rpx;
		margin-bottom: 200rpx;
	}

	.message_per {
		margin-bottom: 20px;
	}

	.user_avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
	}

	.right_my_messages {
		/* background-color: #beebeb; */
		margin-bottom: 20px;
		/* padding: 5px; */
		border-radius: 5px;
		letter-spacing: 1px;
		display: inline-block;
	}

	.right_box {
		display: flex;
		float: inherit;
		justify-content: flex-end;
	}

	.left_user_messages {
		display: flex;
		flex-direction: row;
		margin-bottom: 10px;
	}

	.left_user_messages_text {
		/* background-color: #dcefff; */
		margin-left: 10px;
		margin-bottom: 10px;
		max-width: 80%;
		/* padding: 5px; */
		border-radius: 5px;
		/* padding-left: 10px; */
		letter-spacing: 1px;
	}

	.smile_face {
		width: 28px;
		height: 28px;
		border-radius: 50%;
	}

	.bottom_input {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		max-height: 300px;
		display: flex;
		flex-direction: column;
		/* justify-content: space-between; */
		/* 	padding-left: 25px;
		padding-right: 25px; */
		align-items: center;
		background-color: #fff;
	}

	.container-sender {
		/* margin-top: 30rpx; */
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		width: 85%;
		margin-left: auto;
		margin-right: auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.expression_view {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.voice_view {
		display: flex;
		align-items: center;
	}

	.input_view {
		height: 100%;
		display: flex;
		align-items: center;
		margin-right: 30px;
	}

	/* .input_view input{
		border-radius: 30px;
		border: 1px solid #66596b;
	} */

	.emojis-show {
		width: 95%;
		margin-top: 30rpx;
		display: flex;
		flex-wrap: wrap;
		overflow-y: scroll;
		justify-content: flex-start;
	}

	.emoji-item {
		font-size: 40rpx;
		width: calc(14.28% - 25rpx);
		/* 100% / 7 - 25rpx 用于计算每个表情的宽度，使其每行显示 7 个 */
		margin-right: 25rpx;
		margin-bottom: 30rpx;
		text-align: right;
		/* 使表情在其所在的区域居中 */
		/* background-color: #beebeb; */
	}

	.other-sender {
		width: 95%;
		height: 300px;
		display: flex;
		align-items: self-start;
		flex-wrap: wrap;
		overflow-y: scroll;
	}

	.other-sender-item {
		margin-left: 30rpx;
		margin-right: 50rpx;
		margin-bottom: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.other-sender-image {
		width: 100rpx;
		height: 100rpx;
		background-color: #e2e2e2;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.other-sender-image image {
		width: 60rpx;
		height: 60rpx;
	}

	.other-sender-text {
		margin-top: 20rpx;
	}

	.muiltipily_view image {
		width: 28px;
		height: 28px;
		border-radius: 50%;
	}

	.tip-main {
		width: 150px;
		height: 150px;
		background-color: #fff;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.audio-icon image {
		width: 60px;
		height: 60px;
	}

	.tip-text {
		margin-top: 20rpx;
		font-size: 32rpx;
	}

	.audio-content {
		width: 100%;
		height: 100%;
		color: #000;
		display: flex;
		align-items: center;
		/* padding: 10px; */
		/* padding-left: 10px; */
		/* padding-right: 10px; */
		border-radius: 10px;
	}

	.second-view {
		margin-right: 15rpx;
	}

	.audio-play-icon image {
		width: 60rpx;
		height: 60rpx;
	}

	.image-message image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 10px;
	}

	.image-message {
		width: 160rpx;
		height: 160rpx;
		border-radius: 10px;
	}
	
	.message-video{
		width: 300rpx;
		height: 300rpx;
		border-radius: 20px;
	}
	
	/* .message-video video{
		width: 300rpx;
		height: 300rpx;
		border-radius: 20px;
	} */

	.type-content {
		padding: 10px;
		background-color: #89d961;
		border-radius: 10px;
	}
</style>